package com.lz.comm.net

import okhttp3.Request
import okhttp3.Response


/**
 *  author: you : 2020/04/9
 */
internal class HttpTokenInterceptor {

    //当前token
    private var token: String? = null

    //当前token序列
    private var currentOrdinal = 0L

    @Synchronized
    internal fun setToken(token: String?) {
        this.token = token
        currentOrdinal++
    }

    @Synchronized
    internal fun requestToken(builder: Request.Builder) {
        builder.tag(Long::class.javaObjectType, currentOrdinal).apply { token?.let { addHeader(TOKEN_KEY, it) } }
    }

    /**
     * 检测token是否失效
     */
    internal fun checkTokenExpired(response: Response): Boolean {
        val tag = response.request().tag(Long::class.javaObjectType)
        synchronized(this) {
            return if (tag == currentOrdinal && response.code() == EXPIRED_TOKEN_CODE) {
                token = null
                currentOrdinal++
                true
            } else false
        }
    }

    companion object {

        //请求头token的key
        private const val TOKEN_KEY = "token-key"

        //请求token失效的code
        private const val EXPIRED_TOKEN_CODE = 401
    }
}